/**
 * Created by sam on 16-11-21.
 */
var BufferHelper = require('bufferhelper');
var iconv = require('iconv-lite');
var https = require('https');
var cookie = require('./cookie');

function get(url, fn) {
    var request_timer = null, req = null,flag = true;
    // 请求5秒超时
    request_timer = setTimeout(function () {
        //req.abort();
        console.log('Request Timeout.');
        flag = false;
        if (fn) fn('timeout');
    }, 5000);

    req = https.get(url, function (res) {
        clearTimeout(request_timer);

        // 等待响应10秒超时
        var response_timer = setTimeout(function () {
            res.destroy();
            console.log('Response Timeout.');
            flag = false;
            if (fn) fn('timeout');
        }, 10000);

        var bufferHelper = new BufferHelper();
        res.on('data', function (chunk) {
            bufferHelper.concat(chunk);
        });
        res.on('end', function () {
            clearTimeout(response_timer);
            var html = iconv.decode(bufferHelper.toBuffer(), 'utf-8');
            if (flag && fn) fn(html);
        });
    });
}

function getc(url,num, fn) {
    var request_timer = null, req,flag = true,req_flag = true;
    // 请求5秒超时
    request_timer = setTimeout(function () {
        req.abort();
        console.log('Thread['+num+'] Request Timeout.');
        flag = false;
        req_flag = false;
        if (fn) fn('timeout');
    }, 10000);

        var parse_u=require('url').parse(url,true);
        var isHttp=parse_u.protocol=='http:';
        var ck = cookie.getCookie(num);
        var ag = cookie.getAgent(num);
        console.log('Thread['+num+'] url:'+url);
        //console.log("cookies:"+ck);
        var options={
            host:parse_u.hostname,
            port:parse_u.port||(isHttp?80:443),
            path:parse_u.path,
            method:'GET',
            headers:{
                'Accept':'*/*',
               /* 'Accept-Encoding':'gzip, deflate',
                'Accept-Language':'zh-CN,zh;q=0.8',*/
                'User-Agent':ag,
                'Cookie':ck
            }
        };
        req = require(isHttp ? 'http' : 'https').request(options, function (res) {
            clearTimeout(request_timer);
            // 等待响应10秒超时
            var response_timer = setTimeout(function () {
                //res.destroy();
                console.log('Thread[' + num + '] Response Timeout.');
                flag = false;
                if (req_flag && fn) fn('timeout');
            }, 15000);
            var cookies = res.headers['set-cookie'];
            cookie.setCookies(num, cookies);
            res.on('error',function (e) {
                console.log("res error");
                console.log(e);
            });
            var bufferHelper = new BufferHelper();
            res.on('data', function (chunk) {
                bufferHelper.concat(chunk);
            });
            res.on('end', function () {
                clearTimeout(response_timer);
                var html = iconv.decode(bufferHelper.toBuffer(), "utf-8");
                if (flag && fn) fn(html);
            });
        });
        req.on('error', function (e) {
            console.log('Thread['+num+'] req error'+e.code);
            //console.log(e);
        });
        req.end();
}

function getp() {
    var url = require('url');
    var https = require('https');
    var HttpsProxyAgent = require('https-proxy-agent');

    var proxy = 'http://183.35.209.206:9000';
    console.log('using proxy server %j', proxy);

// HTTPS endpoint for the proxy to connect to
    var endpoint =  'https://www.amazon.com/dp/B010TU7LP2';
    console.log('attempting to GET %j', endpoint);
    var opts = url.parse(endpoint);

// create an instance of the `HttpsProxyAgent` class with the proxy server information
    var agent = new HttpsProxyAgent(proxy);
    opts.agent = agent;

    https.get(opts, function (res) {
        console.log('"response" event!', res.headers);

        var bufferHelper = new BufferHelper();
        res.on('error',function (e) {
            console.log(e);
        });
        res.on('data', function (chunk) {
            bufferHelper.concat(chunk);
        });
        res.on('end', function () {
            var html = iconv.decode(bufferHelper.toBuffer(), 'utf-8');
            //if (flag && fn) fn(html);
            console.log(html);
        });

    });

}

/**
 * 替换所有
 * @param str
 * @param s1
 * @param s2
 * @returns {void|XML|string}
 */
function replaceAll(str,s1,s2) {
        return str.replace(new RegExp(s1, "gm"), s2);
}

/**
 * 替换emoji表情
 * @param str
 * @returns {void|XML|string}
 */
function replaceEmoji(str) {
    return str.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
}

function getDateStr(AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth()+1;//获取当前月份的日期
    var d = dd.getDate();
    return y+"-"+m+"-"+d;
}

module.exports.get = get;
module.exports.getc = getc;
module.exports.replaceAll = replaceAll;
module.exports.replaceEmoji = replaceEmoji;